<?php
/*
 * @Date: 2024-07-18 08:44:33
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-07-23 02:15:10
 */

namespace Ldy\Traits;

trait QsCurl{
    
    protected $curlErrorMsg = '';

    protected $curlRes = '';

    protected $curlHeader=[];

    /**
     * Undocumented function
     *
     * @param [type] $url
     * @param array $data
     * @return $this
     */
    protected function httpGet($url, $data = []) {
        if(!empty($data)) $url = $url . '?' . http_build_query($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_ENCODING, '');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
        if(!empty($this->curlHeader)) curl_setopt($curl, CURLOPT_HTTPHEADER,$this->curlHeader);

        $this->curlRes = curl_exec($curl);

        if (curl_errno($curl)) {
            $this->curlErrorMsg = 'Error GET '.curl_error($curl);
        }
        curl_close($curl);

        return $this;
    }

    protected function setCurlHeader($arr = []){
        $this->curlHeader = $arr;
        return $this;
    }

    /**
     * Undocumented function
     *
     * @param [type] $url
     * @param [type] $data
     * @return $this
     */
    protected function httpPost($url, $data){
        $curl = curl_init();
        
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        // curl_setopt($curl, CURLOPT_HTTPHEADER,['Content-type'=>"application/json"]);

        $this->curlRes = curl_exec($curl);

        if (curl_errno($curl)) {
            $this->curlErrorMsg = 'Error POST '.curl_error($curl);
        }
        curl_close($curl);

        return $this;
    }

    protected function get($json = true){
        if(!$json) return $this->curlRes;

        return json_decode($this->curlRes, true);
    }
}